<!--
 * @Author: liyin 2179253556@qq.com
 * @Date: 2023-09-11 16:45:05
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-05-06 11:33:30
 * @FilePath: HomeView.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="content-box">
    <!-- 加载层 -->
    <div class="loading-flex-box" v-show="loading">
      <dv-loading>加载中...</dv-loading>
    </div>
    <!-- 头部 -->
    <Header ref="header" @setSimeDataOld="setSimeDataOld"></Header>
    <!-- 中间内容部分 -->
    <div class="screenBox" ref="screenBoxHeight" :style="'height:' + screenBoxHeight + 'px;'">
      <div class="screenTop" ref="screenTopRef">
        <div class="left">
          <!-- 选择楼栋 -->
          <div class="floorSelect" @click="isShowSelect = !isShowSelect">
            <el-image :src="require('../assets/img/lou.png')"></el-image>
            <div class="floorName">{{ selectFloorName }}</div>
            <i class="el-icon-caret-bottom"></i>
            <transition enter-active-class="animated fadeIn" leave-active-class="animated fadeOut">
              <div class="selectList" v-if="isShowSelect">
                <div class="items" @click.stop="clickSelect(item)" :class="selectIndex == item.id ? 'active' : ''"
                  v-for="(item, index) in floorList" :key="index">
                  <el-image v-if="selectIndex == item.id" :src="require('../assets/img/icon_choose.png')"
                    alt=""></el-image>
                  <div class="name">{{ item.floor_name }}</div>
                </div>
              </div>
            </transition>
          </div>
          <Title title="实时在寝人数统计"></Title>
          <div class="tips" v-if="timeDataOld == timeData">* 数据每一分钟刷新一次</div>
          <div class="listBox">
            <div class="listTop">
              <div class="listTopLft">
                <span class="tilt">选择时间</span>
                <el-date-picker size="small" v-model="timeData" style="flex: 1;" @change="handleChange" prefix-icon=""
                  type="date" placeholder="选择日期" value-format="yyyy-MM-dd" :clearable="false">
                </el-date-picker>
                <span class="tilt">选择时段</span>
                <el-select size="small" v-model="rule_id" style="flex: 1.2;" @change="changeSelect" placeholder="请选择时段"
                  :clearable="false">
                  <el-option v-for="item in RuleList" :key="item.id" :label="item.remark" :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <div class="listTopRt">
                <div class="irtrm">
                  {{ type == 1 ? '初中部' : '高中部' }}考勤统计：
                </div>
                <!-- 0-缺勤 1-正常 2-迟到、晚归 3-请假 4-补签 5-停宿 6-走读 -->
                <div class="irtrm" @click="ShowDialog3(0, AttendanceInfo.queqing_number, 1)">
                  <div>缺勤 <span style="color: #FF4F27;">{{ AttendanceInfo.queqing_number }}</span></div>
                  <div class="line"></div>
                </div>
                <div class="irtrm" @click="ShowDialog3(3, AttendanceInfo.qingjia_number, 1)">
                  <div>请假 <span>{{ AttendanceInfo.qingjia_number }}</span></div>
                  <div class="line"></div>
                </div>
                <div class="irtrm" v-if="Number(inOut) != 1" @click="ShowDialog3(2, AttendanceInfo.late_gui_number, 1)">
                  <div>晚归 <span>{{ AttendanceInfo.late_gui_number }}</span></div>
                  <div class="line"></div>
                </div>
                <div class="irtrm" v-if="Number(inOut) != 1"
                  @click="ShowDialog3(8, AttendanceInfo.late_gui_qj_number, 1)">
                  <div>晚归请假 <span>{{ AttendanceInfo.late_gui_qj_number }}</span></div>
                  <div class="line"></div>
                </div>
                <div class="irtrm" v-if="Number(inOut) == 1" @click="ShowDialog3(2, AttendanceInfo.late_chu_number, 1)">
                  <div>晚出 <span>{{ AttendanceInfo.late_chu_number }}</span></div>
                  <div class="line"></div>
                </div>
                <div class="irtrm" @click="ShowDialog3(6, AttendanceInfo.zoudu_number, 1)">
                  <div>走读 <span>{{ AttendanceInfo.zoudu_number }}</span></div>
                  <div class="line"></div>
                </div>
                <div class="irtrm" v-if="Number(school_id) == 77"
                  @click="ShowDialog3(7, AttendanceInfo.waichu_number, 1)">
                  <div>外出 <span>{{ AttendanceInfo.waichu_number }}</span></div>
                  <div class="line"></div>
                </div>
                <div class="irtrm" v-if="Number(isLiusu) === 1 && Number(inOut) != 1"
                  @click="ShowDialog3(9, AttendanceInfo.liusu_number, 1)">
                  <div>留宿 <span>{{ AttendanceInfo.liusu_number }}</span></div>
                  <div class="line"></div>
                </div>
                <div class="irtrm" @click="ShowDialog3(5, AttendanceInfo.tingsu_number, 1)">
                  <div>停宿 <span>{{ AttendanceInfo.tingsu_number }}</span></div>
                </div>
              </div>
            </div>
            <div class="listBot">
              <div :class="AttendanceList.length > 8 ? 'items items2' : 'items'" @click="ShowDialog(item)"
                v-for="(item, index) in AttendanceList" :key="index">
                <div>{{ item.layers_name }}人数</div>
                <div>
                  <span>{{ item.queqing_number }}</span>
                  / {{ item.should_number }}
                  <span v-if="Number(item.qingjia_number) != 0">({{ item.qingjia_number }})</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="right" ref="rightRef">
          <Title title='签到时段' ref="titleRef"></Title>
          <div class="chartTil">
            <span></span>
            <span>{{ selectFloorName }}</span>
          </div>
          <div id="chartOne" :style="'height:' + chartOneHeight + 'px;'"></div>
        </div>
      </div>
      <div class="screenBottom" :style="'height:' + screenBottomHeight + 'px;'">
        <div class="left">
          <Title :title='`${selectFloorName}考勤统计`' ref="titleRef"></Title>
          <AttendData :attendData="attendData" :color="color" :attendDataHeight="attendDataHeight" :addTime="addTime"
            :selectRuleName="selectRuleName" @ShowDialog2="ShowDialog2" :school_id="school_id">
          </AttendData>
        </div>
        <div class="center">
          <Title :title='`${selectFloorName}评分名单`' ref="titleRef"></Title>
          <FloorScore :floorScore="floorScore" :floorScoreHeight="floorScoreHeight"
            :nodateFloorScoreHeight="nodateFloorScoreHeight" :floorScoreBol="floorScoreBol"
            @setFloorScoreBol="setFloorScoreBol">
          </FloorScore>
        </div>
        <div class="right">
          <Title :title="Number(mode) == 1 ? '宿舍评分统计' : '学生累计评分统计'" ref="titleRef"></Title>
          <DormitScore :dormitScore="dormitScore" :dormitScore2="dormitScore2" :mode="mode"
            :dormitScoreHeight="dormitScoreHeight" :max2="max2" :max="max">
          </DormitScore>
        </div>
      </div>
    </div>
    <!-- 底部 -->
    <Footer ref="footer"></Footer>
    <transition enter-active-class="animated fadeIn" leave-active-class="animated fadeOut">
      <DetailModify v-if="dialogVisible" @CloseDialog="CloseDialog" :studentList="studentList"
        :selectStatus="selectStatus" :selectTitleName="selectTitleName" @ExportDate="ExportDate"></DetailModify>
    </transition>
  </div>
</template>
<script>
import Header from './Common/Header.vue'
import Footer from './Common/Footer.vue'
import Title from './Common/Title.vue'
import FloorScore from './FloorScore.vue'
import DormitScore from './DormitScore.vue'
import AttendData from './AttendData.vue'
import DetailModify from './DetailModify.vue'
import { mapActions, mapState } from 'vuex'
export default {
  name: 'Home',
  components: {
    Header,
    Footer,
    Title,
    FloorScore,
    DormitScore,
    AttendData,
    DetailModify,
  },
  data() {
    return {
      selectTitleName: '',
      loading: false,
      loadNum: 0,
      floorList: [],
      selectFloorName: '',
      selectFloorId: '',
      RuleList: [],
      RuleTimeList: [],
      screenBoxHeight: 0,
      screenBottomHeight: 0,
      chartOneHeight: 0,
      attendDataHeight: 0,
      floorScoreHeight: 0,
      nodateFloorScoreHeight: 0,
      dormitScoreHeight: 0,
      rowNum: 0,
      myChart1: null,
      myChart2: null,
      floorScore: [],
      floorScoreBol: false,
      dormitScore: [],
      dormitScore2: [],
      attendData: [],
      cycleOneList: [],
      color: ['#05F4F9', '#FD7603', '#EFC241', '#F79F83', '#22A4F8', '#8E98FF', '#2251E5', '#9D40F9', '#4B5C91'],
      timeData: '',
      timeDataOld: '',
      dialogVisible: false,
      selectIndex: '',
      isShowSelect: false,
      type: this.$route.query.type,
      ruleTime: null,
      AttDateTime: null,// 考勤的统计数量定时器
      AttListTime: null,// 每层楼的考勤数量定时器
      TodayRecordTime: null, // 饼图考情定时器
      floorTime: null, // 栋扣分列表定时器
      rankTime: null, // 宿舍排行版定时器
      cycleOneTime: null,// 曲线图定时器
      selectRuleName: '',
      rule_id: '',
      addTime: '',
      AttendanceInfo: {},
      AttendanceList: [],
      CycleOneDate: {},
      studentList: [],
      inOut: '',
      layersName: '',
      studStatus: '',
      max: 0,
      max2: 0,
      changeNum: 0,
      ruleLodNum: 0,
      islodingOne: false,
      islodingTwo: false,
      islodingThird: false,
      islodingFour: false,
      islodingFive: false,
      islodingSix: false,
      islodingSev: false,
      timeNumLoad: 0,
      selectRuleId: '',
      TimeStamp: '',
      selectType: '',
      selectStatus: '',
      isLiusu: this.$route.query.isLiusu,// 是否显示留宿
      isWugan: this.$route.query.isWugan, // 是否属于无感考勤，1是 其他值就是否
      floor_id: this.$route.query.floor_id, // 置顶楼层的id
      mode: this.$route.query.mode, // mode=1 以宿舍为单位扣分 不传或者其他就是学生个人累计评分
      school_id: '',
    }
  },
  async mounted() {
    var that = this
    that.setRouterParams(that.$route.query)
    // 使用clearInterval清除定时器
    clearInterval(that.ruleTime)
    clearInterval(that.cycleOneTime)
    clearInterval(that.AttDateTime)
    clearInterval(that.AttListTime)
    clearInterval(that.TodayRecordTime)
    clearInterval(that.floorTime)
    clearInterval(that.rankTime)
    that.loading = true
    await that.getHeight()
    await that.getFloor()
    // await that.$refs.header.setTimeDate()
    // await that.getTimes()
    await that.getRule()
    this.school_id = this.$refs.header.SchoolInfo.school_id
    await that.getInnit()
    // await that.getAttendanceDate()
    // await that.getAttendanceList()
    // await that.getTodayRecord()  // 获取饼图考情统计
    // await that.getCycleOneDate() //  获取曲线图
    // await that.getfloorScore() // 楼栋扣分列表
    // await that.getRankList() // 获取宿舍排行版
    // that.loading = false
    // setInterval(async () => {
    //   // this.timeNumLoad++
    //   this.TimeStamp++
    //   this.timeDataOld = this.$util.getNowData(this.TimeStamp)
    //   this.setTimeData(`${this.timeDataOld} ${this.$util.getNowTime2(this.TimeStamp)}`) // 存储当前时间 时分秒
    //   this.setHeaderShowTime(`${this.$util.getNowData2(this.TimeStamp)} ${this.$util.getNowTime(this.TimeStamp)}`)
    // }, 1000)
    window.addEventListener('resize', () => {
      setTimeout(async () => {
        await that.setFloorScoreBol(false)
        await that.getHeight()
        await that.getCycleOne()
        await that.getCycleTwo()
        await that.myChart1.resize()
        await that.myChart2.resize()
      }, 100)
    })
  },
  beforeDestroy() {
    clearInterval(this.ruleTime)
    clearInterval(this.cycleOneTime)
    clearInterval(this.AttDateTime)
    clearInterval(this.AttListTime)
    clearInterval(this.TodayRecordTime)
    clearInterval(this.floorTime)
    clearInterval(this.rankTime)
  },
  destroyed() {
    // 使用clearInterval清除定时器
    clearInterval(this.ruleTime)
    clearInterval(this.cycleOneTime)
    clearInterval(this.AttDateTime)
    clearInterval(this.AttListTime)
    clearInterval(this.TodayRecordTime)
    clearInterval(this.floorTime)
    clearInterval(this.rankTime)
  },
  watch: {
    timeDataOld: {
      handler: function (newValue, oldValue) {
        this.timeData = this.timeDataOld
        this.setSelectData(this.timeData)
      }
    },
    // timeData: {
    //   handler: function (newValue, oldValue) {
    //     if (this.timeNumLoad !== 0) {
    //       this.handleChange(newValue)
    //     }
    //   }
    // },
    loadNum: {
      handler: async function (newValue, oldValue) {
        if (this.loadNum !== 0) {
          await this.setTimerConfig1()
          setTimeout(() => {
            this.setTimerConfig3()
            this.setTimerConfig2()
            this.setTimerConfig4()
          }, 500);
        }
      }
    },
    status: {
      handler: function (newValue, oldValue) {
        if (this.loadNum === 0) {
          if (this.islodingOne && this.islodingTwo && this.islodingThird && this.islodingFour && this.islodingFive && this.islodingSix && this.islodingSev) {
            this.loading = false
            this.loadNum = this.loadNum + 1
          }
        }
      }
    },
    selectFloorId: {
      handler: async function (newValue, oldValue) {
        this.setFloorId(newValue)
      }
    },
    selectFloorName: {
      handler: async function (newValue, oldValue) {
        console.log('jinallee')
        this.setFloorName(newValue)
      }
    },
  },
  computed: {
    status() {
      const { islodingOne, islodingTwo, islodingThird, islodingFour, islodingFive, islodingSix, islodingSev, loadNum } = this
      return {
        islodingOne,
        islodingTwo,
        islodingThird,
        islodingFour,
        islodingFive,
        islodingSix,
        loadNum,
        islodingSev
      }
    }
  },
  methods: {
    ...mapActions([
      'setRouterParams',
      'setRuleTimes',
      'setTimeData',
      'setHeaderShowTime',
      'setSelectData',
      'setFloorId',
      'setFloorName'
    ]),
    async getInnit() {
      this.getAttendanceDate()
      this.getAttendanceList()
      this.getTodayRecord()  // 获取饼图考情统计
      this.getCycleOneDate() //  获取曲线图
      this.getfloorScore() // 楼栋扣分列表
      this.getRankList() // 获取宿舍排行版

    },
    setSimeDataOld(val) {
      this.timeDataOld = val
    },
    // async getTimes() {
    //   const { data: res } = await this.$http.post('/TimeStamp')
    //   if (res.code !== 1) return this.$message.error(res.msg)
    //   this.TimeStamp = JSON.parse(res.data.time)
    //   this.timeDataOld = this.$util.getNowData(this.TimeStamp)
    //   this.setTimeData(`${this.timeDataOld} ${this.$util.getNowTime2(this.TimeStamp)}`) // 存储当前时间 时分秒
    //   this.setHeaderShowTime(`${this.$util.getNowData2(this.TimeStamp)} ${this.$util.getNowTime(this.TimeStamp)}`)
    //   // this.$refs.header.dataTime = this.$util.getNowData2(this.TimeStamp)
    //   // this.$refs.header.times = this.$util.getNowTime(this.TimeStamp)
    // },
    // 根据学部获取宿舍楼栋
    async getFloor() {
      const params = {
        type: 'facultyFloor',
        faculty_name: Number(this.type) == 1 ? '初中' : '高中'
      }
      const { data: res } = await this.$http.get('/Dormitory/Floor/', {
        params: params
      })
      if (res.code !== 1) {
        return this.$message.error(res.msg)
      }
      this.floorList = res.data
      if (this.floorList.length > 0) {
        if (this.floor_id) {
          let florIndex = -1
          // 如果上面传了id，就去匹配是否有一样的
          this.floorList.forEach((item, index) => {
            if (Number(item.id) === Number(this.floor_id)) {
              florIndex = index
            }
          })
          if (florIndex !== -1) {
            this.selectFloorName = this.floorList[florIndex].floor_name
            this.selectFloorId = this.floorList[florIndex].id
            this.selectIndex = this.floorList[florIndex].id
          } else {
            this.selectFloorName = this.floorList[0].floor_name
            this.selectFloorId = this.floorList[0].id
            this.selectIndex = this.floorList[0].id
          }
        } else {
          this.selectFloorName = this.floorList[0].floor_name
          this.selectFloorId = this.floorList[0].id
          this.selectIndex = this.floorList[0].id
        }

      }
    },
    // 获取考勤规则
    async getRule() {
      const params = {
        type: 'get_rule',
        floor_name: this.selectFloorName,
        scene: Number(this.isWugan) === 1 ? 'sushewugan' : 'sushe',
        add_time: this.timeData,
        faculty_name: Number(this.type) == 1 ? '初中' : '高中'
      }
      const { data: res } = await this.$http.get('/Attendance/Rule/', {
        params: params
      })
      if (res.code !== 1) {
        this.islodingOne = true
        return this.$message.error(res.msg)
      }
      this.islodingOne = true
      this.RuleList = res.data
      // let arrTime = ['11:21-22:00']
      let arrTime = []
      let arrTime2 = []
      let inNum = 0
      let selIndex = ''
      this.RuleList.forEach(async (item, index) => {
        if (Number(this.selectRuleId) === Number(item.id)) {
          inNum++
          selIndex = index
        }
      })
      this.RuleList.forEach(async (item, index) => {
        arrTime.push(item.start_time + '-' + item.end_time)
        arrTime2.push({
          rule_id: item.id,
          timeRage: item.start_time + '-' + item.end_time,
          start_time: item.start_time,
          end_time: item.end_time,
          add_time: item.add_time,
          in_out: item.in_out,
          rule_name: item.remark
        })
        if (inNum > 0) {
          this.rule_id = this.RuleList[selIndex].id
          this.addTime = this.RuleList[selIndex].add_time
          this.selectRuleName = this.RuleList[selIndex].remark
          this.inOut = this.RuleList[selIndex].in_out
        } else if (Number(item.check) === 1) {
          // 获取考勤的统计数量
          this.rule_id = item.id
          this.addTime = item.add_time
          this.selectRuleName = item.remark
          this.inOut = item.in_out
        }
      })
      this.RuleTimeList = arrTime
      this.setRuleTimes(arrTime2)
    },
    //获取考勤的统计数量
    async getAttendanceDate() {
      const params = {
        type: 'getWuganKaoQinStatistic',
        // floor_name: this.selectFloorName,
        id: this.rule_id,
        add_time: this.addTime,
        faculty_name: Number(this.type) == 1 ? '初中' : '高中'
      }
      const { data: res } = await this.$http.get('/Dormitory/DataScreen/', {
        params: params
      })
      if (res.code !== 1) {
        this.islodingTwo = true
        return this.$message.error(res.msg)
      }
      this.islodingTwo = true
      this.AttendanceInfo = res.data
    },
    // 获取每层楼的考勤数量
    async getAttendanceList() {
      const params = {
        type: 'getLayers',
        floor_id: this.selectFloorId,
        id: this.rule_id,
        add_time: this.addTime,
        faculty_name: Number(this.type) == 1 ? '初中' : '高中'
      }
      const { data: res } = await this.$http.get('/Dormitory/DataScreen/', {
        params: params
      })
      if (res.code !== 1) {
        this.islodingThird = true
        return this.$message.error(res.msg)
      }
      this.islodingThird = true
      this.AttendanceList = res.data
    },
    getHeight() {
      // if (this.loadNum === 0) {
      //   this.loading = true
      // }
      this.screenBoxHeight = document.body.clientHeight - this.$refs.header.$el.clientHeight - this.$refs.footer.$el.clientHeight
      this.screenBottomHeight = this.screenBoxHeight - this.$refs.screenTopRef.clientHeight
      this.chartOneHeight = this.$refs.rightRef.clientHeight - this.$refs.titleRef.$el.clientHeight
      this.attendDataHeight = this.screenBottomHeight - this.$refs.titleRef.$el.clientHeight - 20
      this.floorScoreHeight = this.screenBottomHeight - this.$refs.titleRef.$el.clientHeight - 20
      this.nodateFloorScoreHeight = this.screenBottomHeight - this.$refs.titleRef.$el.clientHeight
      // 排行高度
      this.dormitScoreHeight = this.screenBottomHeight - this.$refs.titleRef.$el.clientHeight
    },
    // 获取曲线图
    async getCycleOneDate() {
      const params = {
        type: 'getKaoqingLineChart',
        floor_name: this.selectFloorName,
        scene_id: Number(this.isWugan) === 1 ? 40 : 28,
        get_time: this.timeData + ' 00:00:00',
        faculty_name: Number(this.type) == 1 ? '初中' : '高中'
      }
      const { data: res } = await this.$http.get('/Dormitory/DataScreen/', {
        params: params
      })
      if (res.code !== 1) {
        this.islodingSev = true
        return this.$message.error(res.msg)
      }
      this.CycleOneDate = res.data
      await this.getCycleOne()
      this.islodingSev = true
    },
    async getCycleOne() {
      this.myChart1 = this.$echarts.init(document.getElementById('chartOne'))
      let data = [];
      let time = []
      const dataIngo = Object.keys(this.CycleOneDate).sort()
      dataIngo.forEach(key => {
        data.push(this.CycleOneDate[key])
        time.push(key + ':00')
      })
      let option = {
        title: {
          text: '',
        },
        tooltip: {
          trigger: 'axis',
          position: 'top',
          backgroundColor: '',
          borderWidth: 0,
          textStyle: {
            color: '#FFFFFF',     // 文字的颜色
            fontWeight: 'normal',    // 文字字体的粗细（'normal'，无样式；'bold'，加粗；'bolder'，加粗的基础上再加粗；'lighter'，变细；数字定义粗细也可以，取值范围100至700）
            fontSize: '14',    // 文字字体大小
          },
          formatter(params) {
            return params[0].name + '\n签到人数 ' + params[0].value + ' 人'
          },
          extraCssText: 'width:120px; white-space:pre-wrap'
        },
        legend: {
          data: [''],
          textStyle: {
            color: '#FFFFFF',
            fontSize: 14
          },
          show: true
        },
        calculable: true,
        grid: {
          top: '20%',
          left: '24px',
          right: '44px',
          bottom: '24px',
          containLabel: true
        },
        xAxis: [
          {
            nameLocation: 'end',
            nameTextStyle: {
              color: '#a0d7de',
              fontSize: 16,
              padding: [50, 0, 0, 10]
            },
            type: 'category',
            boundaryGap: false,
            data: time,
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            offset: 10,
            axisLabel: {
              show: true,
              textStyle: {
                color: '#7BA0D5',
                fontSize: this.nowSize(14)
              }
            },
            axisPointer: { //基准线
              lineStyle: {
                color: '#FFFFFF',
                borderWidth: 2//拐点边框大小
              }
            }

          }
        ],


        yAxis: [
          {
            name: "单位/人数",
            nameTextStyle: {
              color: "#7BA0D5",
              fontSize: this.nowSize(14),
              fontWeight: 'bold',
              fontFamily: "Arial-Bold, Arial",
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: '#7BA0D5',
                fontSize: this.nowSize(14),
                fontWeight: 'bold',
              }
            },
            axisTick: {
              show: false
            },
            axisLine: {
              show: false
            },
            offset: 10,
            splitLine: {
              show: true,
              lineStyle: {
                type: 'solid',
                color: ['transparent']
              }
            }
          }
        ],
        series: [
          {
            name: '',
            type: 'line',
            smooth: true,
            symbolSize: 0,   //设定实心点的大小
            lineStyle: {
              color: '#6BDDF8', //改变折线颜色
              borderWidth: 2//拐点边框大小
            },
            lineWidth: 2,
            itemStyle: {
              normal: {
                areaStyle: { type: 'default' },
                color: this.$echarts.graphic.LinearGradient(
                  0, 0, 0, 1,
                  [
                    { offset: 0, color: '#6BDDF8' },
                    { offset: 1, color: 'rgba(107,221,248,0)' }
                  ]
                ),
                borderColor: '#6BDDF8',//拐点边框颜色
                borderWidth: 2//拐点边框大小
              }
            },
            data: data
          },

        ]
      }
      this.myChart1.setOption(option, true)
    },
    // 获取饼图考情统计
    async getTodayRecord() {
      const params = {
        type: 'attendanceStatisticsNew',
        floor_id: this.selectFloorId,
        id: this.rule_id,
        add_time: this.addTime,
        faculty_name: Number(this.type) == 1 ? '初中' : '高中'
      }
      const { data: res } = await this.$http.get('/Dormitory/DataScreen/', {
        params: params
      })
      if (res.code !== 1) {
        this.islodingFour = true
        return this.$message.error(res.msg)
      }
      this.attendData = []
      let data = res.data[0]
      let wanguiNum = Number(this.inOut) !== 1 ? data.number.late_gui : data.number.late_chu
      let qiandaoParent = (100 * (Number(data.number.normal) / (Number(res.total.total_all) - (Number(this.school_id) !== 77 ? 0 : Number(data.number.waichu)) - Number(wanguiNum) - Number(data.number.late_gui_qj) - Number(data.number.zoudu) - Number(data.number.leave) - Number(data.number.stay_stop) - Number(data.number.liusu)))).toFixed(2)
      // 0-缺勤 1-正常 2-迟到、晚归 3-请假 4-补签 5-停宿 6-走读 7-外出 8 晚归请假 9留宿
      this.attendData.push({
        value: data.number.normal,
        percent: qiandaoParent,
        status: 1,
        name: '签到',
      })
      this.attendData.push({
        value: data.number.absence,
        percent: data.rate.absence_rate,
        status: 0,
        name: '缺勤',
      })
      if (Number(this.inOut) !== 1) {
        this.attendData.push({
          value: data.number.late_gui_qj,
          percent: data.rate.late_gui_qj_rate,
          name: '晚归请假',
          status: 8,
        })
      }
      // 暂时是未来学校展示外出状态
      if (Number(this.school_id) === 77) {
        this.attendData.push({
          value: data.number.waichu,
          percent: data.rate.waichu_rate,
          status: 7,
          name: '外出',
        })
      }
      if (Number(this.isLiusu) === 1 && Number(this.inOut) != 1) {
        this.attendData.push({
          value: data.number.liusu,
          percent: data.rate.late_liusu_rate,
          status: 9,
          name: '留宿',
        })
      }

      this.attendData.push({
        value: data.number.stay_stop,
        percent: data.rate.stay_stop_rate,
        name: '停宿',
        status: 5,
      })
      if (Number(this.inOut) !== 1) {
        this.attendData.push({
          value: data.number.late_gui,
          percent: data.rate.late_gui_rate,
          status: 2,
          name: '晚归',
        })
      } else {
        this.attendData.push({
          value: data.number.late_chu,
          percent: data.rate.late_chu_rate,
          name: '晚出',
          status: 2,
        })
      }
      this.attendData.push({
        value: data.number.zoudu,
        percent: data.rate.zoudu_rate,
        name: '走读',
        status: 6,
      })
      this.attendData.push({
        value: data.number.leave,
        percent: data.rate.leave_rate,
        status: 3,
        name: '请假',
      })
      this.attendDataTotal = data.total
      // 发起饼图请求
      await this.getCycleTwo()
      this.islodingFour = true
    },
    // 让文字根据屏幕自适应
    nowSize(val) {
      var nowClientWidth = document.documentElement.clientWidth
      return val * (nowClientWidth / 1920)
    },
    // 让文字根据屏幕自适应
    nowSize2(val) {
      var nowClientHeight = document.documentElement.clientHeight
      return val * (nowClientHeight / 1080)
    },
    async getCycleTwo() {
      this.myChart2 = this.$echarts.init(document.getElementById('container1'))
      var option = {
        tooltip: {},
        color: this.color,
        series: [
          {
            name: '访问来源',
            type: 'pie',
            radius: ['70%', '100%'],
            center: ['50%', '50%'],
            avoidLabelOverlap: false,
            clockWise: false, // 默认逆时针
            normal: {
              borderWidth: 2,
              borderColor: '#fff'
            },
            label: {
              show: false,
              position: 'center',
              normal: {
                show: true,
                position: 'center',
                formatter: '{total|' + this.attendDataTotal + '}' + '\n\r' + '{active|总人数}',
                rich: {
                  total: {
                    fontSize: this.nowSize(30),
                    fontFamily: "Arial-Bold, Arial",
                    color: '#ffffff',
                    lineHeight: this.nowSize2(34),
                    fontWeight: 'bold'
                  },
                  active: {
                    fontFamily: "Microsoft YaHei-Bold, Microsoft YaHei",
                    fontSize: this.nowSize(14),
                    color: '#ffffff',
                    lineHeight: this.nowSize2(34),
                    fontWeight: 'bold'
                  },
                }
              },
              emphasis: {
                show: true
              }
            },
            data: this.attendData
          }
        ]
      }
      this.myChart2.setOption(option, true)
    },
    async getfloorScore() {
      const params = {
        type: 'person_score_sort',
        floor_name: this.selectFloorName,
        faculty_name: Number(this.type) == 1 ? '初中部' : '高中部'
      }
      await this.$http({
        url: '/Dormitory/DataScreen/',
        method: 'get',
        params: params,
        faculty_name: Number(this.type) == 1 ? '初中' : '高中'
      }).then((res) => {
        if (res.data.code !== 1) {
          this.islodingFive = true
          return;
        }
        this.$nextTick(async () => {
          let arr = []
          if (res.data.data.length > 0) {
            res.data.data.forEach(async (item, index) => {
              arr.push([
                // index+1,
                item.student_name,
                item.class_name,
                item.room_name,
                '<span style=' + (Number(item.item_type) === 1 ? "'color:#FF4F27;font-weight: bold;'" : "'color: #66FFFF;font-weight: bold;'") + '>' + (Number(item.item_type) === 1 ? item.score : '+' + item.score) + '分</span>'
              ])
            })
          }
          this.floorScore = arr
          this.islodingFive = true
        })
      }).catch((err) => {
        console.log(err)
      })
    },
    // 获取宿舍排行版
    async getRankList() {
      const params = {
        type: 'room_score_sort',
        floor_name: this.selectFloorName,
      }
      if (Number(this.mode) === 1) {
        params.flag = 'room'
      }
      await this.$http({
        url: '/Dormitory/DataScreen/',
        method: 'get',
        params: params,
        faculty_name: Number(this.type) == 1 ? '初中' : '高中'
      }).then(async (res) => {
        if (res.data.code !== 1) {
          // this.loading = false
          this.islodingSix = true
          return false
        }
        this.dormitScore = res.data.data.kf
        if (this.dormitScore.length > 0) {
          this.dormitScore.forEach((item, index) => {
            item.rankNum = index + 1
          })
          this.max = await this.getMax(this.dormitScore)
        }
        this.dormitScore2 = res.data.data.jf
        if (this.dormitScore2.length > 0) {
          this.dormitScore2.forEach((item, index) => {
            item.rankNum = index + 1
          })
          this.max2 = await this.getMax(this.dormitScore2)
        }
        // if (this.loadNum === 0) {
        //   this.setTimerConfig1()
        //   this.setTimerConfig3()
        //   this.setTimerConfig2()
        //   this.setTimerConfig4()
        // }
        // this.loading = false
        // this.loadNum = this.loadNum + 1
        this.islodingSix = true
      }).catch((err) => {
        console.log(err)
      })
    },
    // 获取评分的分数最大值
    async getMax(data) {
      var barArry = []
      data.forEach((item, index) => {
        barArry.push(Math.abs(Number(Number(this.mode) == 1 ? item.room_score : item.score)))
      })
      return Math.max.apply(null, barArry)
    },
    // 等页面加载全部结束之后处理定时器逻辑
    setTimerConfig1() {
      this.ruleTime = setInterval(async () => {
        if (this.timeDataOld === this.timeData) {
          // 如果是选择当天日期
          // 看看是否要调用考情规则和曲线图接口
          this.getRule()
          // let num = 0
          // // this.RuleTimeList = ['18:30:00-19:10:00', '19:12:00-19:13:00', '19:16:00-19:18:00']
          // // 判断当前时间是否在考情范围内
          // this.RuleTimeList.forEach(async (item) => {
          //   if (this.isDuringDate(this.timeData.replaceAll('-', '/') + ' ' + (item.length > 5 ? item.split('-')[0] : item.split('-')[0] + ':00'), this.timeData.replaceAll('-', '/') + ' ' + (item.length > 5 ? item.split('-')[1] : item.split('-')[1] + ':59'))) {
          //     num++
          //   }
          // })
          // // num>0 证明在这个考情时段内，就开启定时器
          // if (num > 0) {
          //   if (this.ruleLodNum === 0) {
          //     this.getRule() // 更新选中规则选项，但是只需要更新一次就好了
          //   }
          //   this.ruleLodNum++
          // } else {
          //   this.ruleLodNum = 0
          // }
        }
      }, 1000 * 60)
    },
    setTimerConfig2() {
      this.cycleOneTime = setInterval(async () => {
        if (this.timeDataOld === this.timeData) {
          // 如果是选择当天日期
          // 看看是否要调用考情规则和曲线图接口
          let num = 0
          // 判断当前时间是否在考情范围内
          this.RuleTimeList.forEach(async (item) => {
            if (this.isDuringDate(this.timeData.replaceAll('-', '/') + ' ' + (item.length > 5 ? item.split('-')[0] : item.split('-')[0] + ':00'), this.timeData.replaceAll('-', '/') + ' ' + (item.length > 5 ? item.split('-')[1] : item.split('-')[1] + ':59'))) {
              num++
            }
          })
          // num>0 证明在这个考情时段内，就开启定时器
          if (num > 0) {
            this.getCycleOneDate()
          }
        }
      }, 1000 * 60)

    },
    setTimerConfig3() {
      if (this.timeDataOld === this.timeData) {
        this.AttDateTime = setInterval(async () => {
          this.getAttendanceDate() // 考勤的统计数量定时器
        }, 1000 * 60)
        this.AttListTime = setInterval(async () => {
          this.getAttendanceList() // 每层楼的考勤数量
        }, 1000 * 60)
        this.TodayRecordTime = setInterval(async () => {
          this.getTodayRecord() // 饼图考情统计
        }, 1000 * 60)
      }
    },
    setTimerConfig4() {
      // 楼栋扣分列表定时器
      // 只有当数据不为0的时候才开启定时器 没半个小时加载一次
      if (this.floorScore.length > 0) {
        this.floorTime = setInterval(async () => {
          this.floorScoreBol = true
          this.getfloorScore()
        }, 1000 * 60 * 30)
      }
      // 宿舍排行版定时器
      if (this.dormitScore.length > 0 || this.dormitScore2.length > 0) {
        this.rankTime = setInterval(async () => {
          this.getRankList()
        }, 1000 * 60 * 30)
      }
    },
    setFloorScoreBol(bol) {
      this.floorScoreBol = bol
    },
    isDuringDate(beginDateStr, endDateStr) {
      console.log(beginDateStr, endDateStr, 'kkkkkkkkk')
      var curDate = new Date()
      var beginDate = new Date(beginDateStr)
      var endDate = new Date(endDateStr)
      if (curDate >= beginDate && curDate <= endDate) {
        console.log('jinlaile')
        return true
      }
      return false
    },
    // 获取考勤学生名单
    async getStudentList(val, status, type) {
      const params = {
        type: 'getNameListNew',
        id: this.rule_id,
        add_time: this.addTime,
        layers_name: val,
        status: status,
        faculty_name: Number(this.type) == 1 ? '初中' : '高中'
      }
      if (Number(type) === 2) {
        params.floor_name = this.selectFloorName
      }
      const { data: res } = await this.$http.get('/Dormitory/DataScreen/', {
        params: params
      })
      if (res.code !== 1) {
        return this.$message.error(res.msg)
      }
      this.studentList = this.sortedItems(res.data.list)
      this.selectStatus = status
      this.dialogVisible = true
    },
    // 按照时间倒序排列 越晚的越靠前
    sortedItems(arr) {
      return arr.slice().sort((a, b) => { // 使用slice()避免直接修改原数组
        let obj1 = a['attendance_time']
        let obj2 = b['attendance_time']
        const val1 = Math.floor(new Date(obj1).getTime() / 1000)
        const val2 = Math.floor(new Date(obj2).getTime() / 1000)
        return val2 - val1
      })
    },
    // 导出数据
    async ExportDate() {
      const params = {
        type: 'nameListDownloadNew',
        floor_name: Number(this.selectType) == 2 ? this.selectFloorName : '',
        id: this.rule_id,
        add_time: this.addTime,
        layers_name: this.layersName,
        status: this.studStatus,
        faculty_name: Number(this.type) == 1 ? '初中' : '高中'
      }
      const { data: res } = await this.$http.get('/Dormitory/DataScreen/', {
        params: params
      })
      if (res.code !== 1) {
        return this.$message.error(res.msg)
      }
      window.location.href = res.data.url
    },
    CloseDialog() {
      this.layersName = ''
      this.studStatus = ''
      this.dialogVisible = false
    },
    ShowDialog(item) {
      if (Number(item.queqing_number) > 0) {
        this.layersName = item.layers_name
        this.studStatus = 0
        this.selectType = 2
        this.selectTitleName = `${this.selectFloorName}-${this.selectRuleName}`
        this.getStudentList(item.layers_name, 0, 2)
      }
    },
    ShowDialog2(status, num, type) {
      if (Number(num) > 0) {
        this.layersName = ''
        this.studStatus = status
        this.selectType = type
        this.selectTitleName = `${this.selectFloorName}-${this.selectRuleName}`
        this.getStudentList('', status, type)
      }
    },
    ShowDialog3(status, num, type) {
      if (Number(num) > 0) {
        this.layersName = ''
        this.studStatus = status
        this.selectType = type
        this.selectTitleName = `${this.type == 1 ? '初中部' : '高中部'}-${this.selectRuleName}`
        this.getStudentList('', status, type)
      }
    },
    // 楼栋发生变化时候
    async clickSelect(item) {
      this.selectRuleId = this.rule_id
      this.loading = true
      this.selectFloorName = item.floor_name
      this.selectFloorId = item.id
      this.selectIndex = item.id
      this.isShowSelect = false
      this.islodingOne = false
      this.islodingTwo = false
      this.islodingThird = false
      this.islodingFour = false
      this.islodingFive = false
      this.islodingSix = false
      clearInterval(this.ruleTime)
      clearInterval(this.AttDateTime)
      clearInterval(this.AttListTime)
      clearInterval(this.TodayRecordTime)
      clearInterval(this.cycleOneTime)
      clearInterval(this.floorTime)
      clearInterval(this.rankTime)
      await this.getRule()
      this.getCycleOneDate() //  获取曲线图
      this.getAttendanceDate() // 获取考勤的统计数量
      this.getAttendanceList() // 获取每层楼的考勤数量
      this.getTodayRecord() // 获取饼图考情统计
      this.getfloorScore() // 楼栋扣分列表
      this.getRankList() // 获取宿舍排行版
      let tiimer = setInterval(async () => {
        if (this.islodingOne && this.islodingTwo && this.islodingThird && this.islodingFour && this.islodingFive && this.islodingSix) {
          this.loading = false
          clearInterval(tiimer)
        }
      }, 100);
      await setTimeout(() => {
        this.setTimerConfig1()
        this.setTimerConfig3()
        this.setTimerConfig2()
        this.setTimerConfig4()
      }, 500);

    },
    // 选择规则
    async changeSelect(val) {
      this.loading = true
      this.rule_id = val
      this.addTime = this.RuleList.find(item => item.id == val).add_time
      this.selectRuleName = this.RuleList.find(item => item.id == val).remark
      this.inOut = this.RuleList.find(item => item.id == val).in_out
      this.islodingOne = false
      this.islodingTwo = false
      this.islodingThird = false
      this.islodingFour = false
      this.islodingFive = false
      this.islodingSix = false
      clearInterval(this.AttDateTime)
      clearInterval(this.AttListTime)
      clearInterval(this.TodayRecordTime)
      clearInterval(this.cycleOneTime)
      this.getCycleOneDate() //  获取曲线图
      this.getAttendanceDate() //获取考勤的统计数量
      this.getAttendanceList() // 获取每层楼的考勤数量
      this.getTodayRecord() // 获取饼图考情统计
      let tiimer2 = setInterval(async () => {
        if (this.islodingTwo && this.islodingThird && this.islodingFour) {
          this.loading = false
          clearInterval(tiimer2)
        }
      }, 100);
      await setTimeout(() => {
        this.setTimerConfig3()
        this.setTimerConfig2()
      }, 500);
    },
    // 选择时间 
    async handleChange(value) {
      this.selectRuleId = this.rule_id
      // 选择时间的时候需要存储切换的日期
      this.setSelectData(value)
      this.loading = true
      if (value !== null) {
        this.timeData = value
      } else {
        this.timeData = ''
      }
      this.islodingOne = false
      this.islodingTwo = false
      this.islodingThird = false
      this.islodingFour = false
      this.islodingFive = false
      this.islodingSix = false
      clearInterval(this.ruleTime)
      clearInterval(this.AttDateTime)
      clearInterval(this.AttListTime)
      clearInterval(this.TodayRecordTime)
      clearInterval(this.cycleOneTime)
      await this.getRule()
      this.getCycleOneDate() //  获取曲线图
      // 拿到规则之后再重新加载新的数据
      this.getAttendanceDate() //获取考勤的统计数量
      this.getAttendanceList() // 获取每层楼的考勤数量
      this.getTodayRecord() // 获取饼图考情统计
      let tiimer3 = setInterval(async () => {
        if (this.islodingOne && this.islodingTwo && this.islodingThird && this.islodingFour) {
          this.loading = false
          clearInterval(tiimer3)
        }
      }, 100);
      await setTimeout(() => {
        this.ruleLodNum = 0
        this.setTimerConfig1()
        this.setTimerConfig3()
        this.setTimerConfig2()
      }, 500);
    }
  }
}
</script>
<style lang="less" scoped></style>
